<template>
  <div class="user-profile-page">
    <div class="page-container">
      <div class="card profile-card">
        <div class="profile-header">
          <div class="avatar-container">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><User /></el-icon>
            </el-upload>
            <div class="upload-tip">点击更换头像</div>
          </div>
          
          <div class="user-basic-info">
            <h1 class="user-name">{{ userInfo.nickname || userInfo.userName }}</h1>
            <div class="user-meta">
              <span class="user-id">ID: {{ userInfo.id }}</span>
              <span class="user-email">{{ userInfo.email }}</span>
              <span class="user-role">{{ getUserRoleText(userInfo.role) }}</span>
            </div>
            <div class="user-stats">
              <div class="stat-item">
                <span class="stat-value">{{ createdActivityCount }}</span>
                <span class="stat-label">创建活动</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ participatedActivityCount }}</span>
                <span class="stat-label">参与活动</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ commentCount }}</span>
                <span class="stat-label">发表评价</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="profile-content">
        <div class="left-panel">
          <div class="card">
            <h2 class="section-title">个人信息</h2>
            <el-form
              ref="profileFormRef"
              :model="profileForm"
              :rules="profileRules"
              label-width="100px"
              class="profile-form"
            >
              <el-form-item label="用户名" prop="userName">
                <el-input v-model="profileForm.userName" disabled />
                <div class="form-tip">用户名不可修改</div>
              </el-form-item>
              
              <el-form-item label="昵称" prop="nickname">
                <el-input v-model="profileForm.nickname" placeholder="请输入昵称" />
              </el-form-item>
              
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
              </el-form-item>
              
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="profileForm.phone" placeholder="请输入手机号" />
              </el-form-item>
              
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="profileForm.gender">
                  <el-radio value="MALE">男</el-radio>
                  <el-radio value="FEMALE">女</el-radio>
                  <el-radio value="UNKNOWN">保密</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="生日" prop="birthdate">
                <el-date-picker
                  v-model="profileForm.birthdate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              
              <el-form-item label="个人简介" prop="bio">
                <el-input
                  v-model="profileForm.bio"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入个人简介"
                  maxlength="200"
                  show-word-limit
                />
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" :loading="updatingProfile" @click="handleUpdateProfile">保存修改</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        
        <div class="right-panel">
          <div class="card">
            <h2 class="section-title">修改密码</h2>
            <el-form
              ref="passwordFormRef"
              :model="passwordForm"
              :rules="passwordRules"
              label-width="100px"
              class="password-form"
            >
              <el-form-item label="当前密码" prop="currentPassword">
                <el-input
                  v-model="passwordForm.currentPassword"
                  type="password"
                  placeholder="请输入当前密码"
                  show-password
                />
              </el-form-item>
              
              <el-form-item label="新密码" prop="newPassword">
                <el-input
                  v-model="passwordForm.newPassword"
                  type="password"
                  placeholder="请输入新密码"
                  show-password
                />
                <div class="form-tip">密码长度至少8位，包含字母和数字</div>
              </el-form-item>
              
              <el-form-item label="确认新密码" prop="confirmPassword">
                <el-input
                  v-model="passwordForm.confirmPassword"
                  type="password"
                  placeholder="请再次输入新密码"
                  show-password
                />
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" :loading="updatingPassword" @click="handleUpdatePassword">修改密码</el-button>
              </el-form-item>
            </el-form>
          </div>
          
          <div class="card">
            <h2 class="section-title">账号安全</h2>
            <div class="security-section">
              <div class="security-item">
                <div class="security-label">邮箱验证</div>
                <div class="security-status">
                  <el-tag :type="userInfo.emailVerified ? 'success' : 'warning'">
                    {{ userInfo.emailVerified ? '已验证' : '未验证' }}
                  </el-tag>
                </div>
                <div class="security-action">
                  <el-button
                    v-if="!userInfo.emailVerified"
                    type="text"
                    :loading="sendingVerification"
                    @click="sendEmailVerification"
                  >
                    发送验证码
                  </el-button>
                </div>
              </div>
              
              <div class="security-item">
                <div class="security-label">手机验证</div>
                <div class="security-status">
                  <el-tag :type="userInfo.phoneVerified ? 'success' : 'warning'">
                    {{ userInfo.phoneVerified ? '已验证' : '未验证' }}
                  </el-tag>
                </div>
                <div class="security-action">
                  <el-button
                    v-if="!userInfo.phoneVerified && userInfo.phone"
                    type="text"
                    :loading="sendingVerification"
                    @click="sendPhoneVerification"
                  >
                    发送验证码
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 邮箱验证对话框 -->
      <el-dialog
        v-model="showEmailVerifyDialog"
        title="邮箱验证"
        width="500px"
      >
        <el-form :model="verifyForm" :rules="verifyRules" ref="verifyFormRef">
          <el-form-item label="验证码" prop="verificationCode">
            <el-input
              v-model="verifyForm.verificationCode"
              placeholder="请输入邮箱收到的验证码"
              maxlength="6"
              show-word-limit
            >
              <template #append>
                <el-button
                  :disabled="countdown > 0"
                  type="text"
                  @click="resendVerificationCode('email')"
                >
                  {{ countdown > 0 ? `${countdown}s后重发` : '重新发送' }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showEmailVerifyDialog = false">取消</el-button>
            <el-button type="primary" :loading="verifying" @click="submitEmailVerification">验证</el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 手机验证对话框 -->
      <el-dialog
        v-model="showPhoneVerifyDialog"
        title="手机验证"
        width="500px"
      >
        <el-form :model="verifyForm" :rules="verifyRules" ref="verifyFormRef">
          <el-form-item label="验证码" prop="verificationCode">
            <el-input
              v-model="verifyForm.verificationCode"
              placeholder="请输入手机收到的验证码"
              maxlength="6"
              show-word-limit
            >
              <template #append>
                <el-button
                  :disabled="countdown > 0"
                  type="text"
                  @click="resendVerificationCode('phone')"
                >
                  {{ countdown > 0 ? `${countdown}s后重发` : '重新发送' }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showPhoneVerifyDialog = false">取消</el-button>
            <el-button type="primary" :loading="verifying" @click="submitPhoneVerification">验证</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { updateUserProfile, getUserStatistics, changePassword, sendVerificationCode, getCurrentUser } from '../api/user'
import { ElMessage } from 'element-plus'
import { User } from '@element-plus/icons-vue'

export default {
  name: 'UserProfile',
  components: {
    User
  },
  setup() {
    const router = useRouter()
    const profileFormRef = ref(null)
    const passwordFormRef = ref(null)
    const verifyFormRef = ref(null)
    
    // 状态
    const updatingProfile = ref(false)
    const updatingPassword = ref(false)
    const sendingVerification = ref(false)
    const verifying = ref(false)
    const countdown = ref(0)
    const showEmailVerifyDialog = ref(false)
    const showPhoneVerifyDialog = ref(false)
    const currentVerifyType = ref('')
    
    // 上传URL（实际项目中应该从环境变量或配置中获取）
    const uploadUrl = '/api/upload/avatar'
    
    // 用户信息
    const userInfo = ref({})
    
    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        const response = await getCurrentUser()
        if (response.code === 200 && response.data) {
          userInfo.value = response.data
          // 同时更新localStorage中的用户信息
          localStorage.setItem('userInfo', JSON.stringify(response.data))
        }
      } catch (error) {
        console.error('获取用户信息失败', error)
      }
    }
    
    // 统计数据
    const createdActivityCount = ref(0)
    const participatedActivityCount = ref(0)
    const commentCount = ref(0)
    
    // 个人信息表单
    const profileForm = reactive({
      userName: '',
      nickname: '',
      email: '',
      phone: '',
      gender: 'UNKNOWN',
      birthdate: '',
      bio: ''
    })
    
    const profileRules = {
      nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { min: 2, max: 20, message: '昵称长度在2-20个字符', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      phone: [
        {
          pattern: /^1[3-9]\d{9}$/,
          message: '请输入正确的手机号码',
          trigger: 'blur',
          required: false
        }
      ],
      bio: [
        { max: 200, message: '个人简介不能超过200个字符', trigger: 'blur' }
      ]
    }
    
    // 密码修改表单
    const passwordForm = reactive({
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    const passwordRules = {
      currentPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        {
          pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,}$/,
          message: '密码长度至少8位，包含字母和数字',
          trigger: 'blur'
        }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== passwordForm.newPassword) {
              return callback(new Error('两次输入的密码不一致'))
            }
            callback()
          },
          trigger: 'blur'
        }
      ]
    }
    
    // 验证码表单
    const verifyForm = reactive({
      verificationCode: ''
    })
    
    const verifyRules = {
      verificationCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { pattern: /^\d{6}$/, message: '请输入6位数字验证码', trigger: 'blur' }
      ]
    }
    
    // 获取用户统计数据
    const fetchUserStatistics = async () => {
      try {
        const response = await getUserStatistics()
        const stats = response.data || {}
        createdActivityCount.value = stats.createdActivityCount || 0
        participatedActivityCount.value = stats.participatedActivityCount || 0
        commentCount.value = stats.commentCount || 0
      } catch (error) {
        console.error('获取用户统计数据失败', error)
      }
    }
    
    // 初始化表单数据
    const initFormData = () => {
      if (userInfo.value) {
        profileForm.userName = userInfo.value.userName || ''
        profileForm.nickname = userInfo.value.nickname || ''
        profileForm.email = userInfo.value.email || ''
        profileForm.phone = userInfo.value.phone || ''
        profileForm.gender = userInfo.value.gender || 'UNKNOWN'
        profileForm.birthdate = userInfo.value.birthdate || ''
        profileForm.bio = userInfo.value.bio || ''
      }
    }
    
    // 更新个人信息
    const handleUpdateProfile = async () => {
      if (!profileFormRef.value) return
      
      try {
        await profileFormRef.value.validate()
        updatingProfile.value = true
        
        await updateUserProfile({
          nickname: profileForm.nickname,
          email: profileForm.email,
          phone: profileForm.phone,
          gender: profileForm.gender,
          birthdate: profileForm.birthdate,
          bio: profileForm.bio
        })
        
        // 更新用户信息
        await fetchUserInfo()
        
        ElMessage.success('个人信息更新成功')
      } catch (error) {
        if (error.response?.data?.message) {
          ElMessage.error(error.response.data.message)
        } else {
          ElMessage.error('更新失败，请重试')
        }
      } finally {
        updatingProfile.value = false
      }
    }
    
    // 修改密码
    const handleUpdatePassword = async () => {
      if (!passwordFormRef.value) return
      
      try {
        await passwordFormRef.value.validate()
        updatingPassword.value = true
        
        await changePassword({
          currentPassword: passwordForm.currentPassword,
          newPassword: passwordForm.newPassword
        })
        
        ElMessage.success('密码修改成功，请重新登录')
        
        // 清空表单
        passwordForm.currentPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
        
        // 登出用户
        setTimeout(() => {
          // 清除本地存储的认证信息
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          router.push('/login')
        }, 1500)
      } catch (error) {
        if (error.response?.data?.message) {
          ElMessage.error(error.response.data.message)
        } else {
          ElMessage.error('修改失败，请重试')
        }
      } finally {
        updatingPassword.value = false
      }
    }
    
    // 头像上传成功处理
    const handleAvatarSuccess = async (response) => {
      if (response.code === 200 && response.data) {
        // 更新头像URL
        await updateUserProfile({ avatar: response.data.url })
        // 更新用户信息
        await fetchUserInfo()
        ElMessage.success('头像更新成功')
      } else {
        ElMessage.error('头像更新失败')
      }
    }
    
    // 头像上传前校验
    const beforeAvatarUpload = (file) => {
      const isLt2M = file.size / 1024 / 1024 < 2
      const isImg = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
      
      if (!isImg) {
        ElMessage.error('只支持 jpg, png, gif 格式的图片')
        return false
      }
      
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB')
        return false
      }
      
      return true
    }
    
    // 发送邮箱验证码
    const sendEmailVerification = async () => {
      try {
        sendingVerification.value = true
        await sendVerificationCode('email', userInfo.value.email)
        ElMessage.success('验证码已发送，请查收')
        showEmailVerifyDialog.value = true
        currentVerifyType.value = 'email'
        startCountdown()
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '发送失败')
      } finally {
        sendingVerification.value = false
      }
    }
    
    // 发送手机验证码
    const sendPhoneVerification = async () => {
      try {
        sendingVerification.value = true
        await sendVerificationCode('phone', userInfo.value.phone)
        ElMessage.success('验证码已发送，请查收')
        showPhoneVerifyDialog.value = true
        currentVerifyType.value = 'phone'
        startCountdown()
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '发送失败')
      } finally {
        sendingVerification.value = false
      }
    }
    
    // 重新发送验证码
    const resendVerificationCode = async (type) => {
      currentVerifyType.value = type
      const target = type === 'email' ? userInfo.value.email : userInfo.value.phone
      
      try {
        await sendVerificationCode(type, target)
        ElMessage.success('验证码已重新发送')
        startCountdown()
      } catch (error) {
        ElMessage.error('发送失败')
      }
    }
    
    // 提交邮箱验证
    const submitEmailVerification = async () => {
      await submitVerification('email')
    }
    
    // 提交手机验证
    const submitPhoneVerification = async () => {
      await submitVerification('phone')
    }
    
    // 提交验证
    const submitVerification = async (type) => {
      if (!verifyFormRef.value) return
      
      try {
        await verifyFormRef.value.validate()
        verifying.value = true
        
        ElMessage.success('验证功能开发中')
        
        if (type === 'email') {
          showEmailVerifyDialog.value = false
        } else {
          showPhoneVerifyDialog.value = false
        }
        
        // 更新用户信息
        await fetchUserInfo()
        
        // 清空验证表单
        verifyForm.verificationCode = ''
      } catch (error) {
        ElMessage.error('验证失败')
      } finally {
        verifying.value = false
      }
    }
    
    // 开始倒计时
    const startCountdown = () => {
      countdown.value = 60
      const timer = setInterval(() => {
        if (countdown.value > 0) {
          countdown.value--
        } else {
          clearInterval(timer)
        }
      }, 1000)
    }
    
    // 获取用户角色文本
    const getUserRoleText = (role) => {
      const roleMap = {
        'ADMIN': '管理员',
        'ORGANIZER': '活动组织者',
        'USER': '普通用户'
      }
      return roleMap[role] || '普通用户'
    }
    
    onMounted(() => {
      fetchUserInfo()
      initFormData()
      fetchUserStatistics()
    })
    
    return {
      userInfo,
      createdActivityCount,
      participatedActivityCount,
      commentCount,
      profileForm,
      profileRules,
      passwordForm,
      passwordRules,
      verifyForm,
      verifyRules,
      profileFormRef,
      passwordFormRef,
      verifyFormRef,
      updatingProfile,
      updatingPassword,
      sendingVerification,
      verifying,
      countdown,
      showEmailVerifyDialog,
      showPhoneVerifyDialog,
      uploadUrl,
      handleUpdateProfile,
      handleUpdatePassword,
      handleAvatarSuccess,
      beforeAvatarUpload,
      sendEmailVerification,
      sendPhoneVerification,
      resendVerificationCode,
      submitEmailVerification,
      submitPhoneVerification,
      getUserRoleText
    }
  }
}
</script>

<style scoped>
.user-profile-page {
  min-height: calc(100vh - 180px);
}

.profile-card {
  margin-bottom: 24px;
}

.profile-header {
  display: flex;
  gap: 40px;
  padding: 30px;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  cursor: pointer;
  transition: opacity 0.3s;
}

.avatar:hover {
  opacity: 0.9;
}

.avatar-uploader-icon {
  width: 120px;
  height: 120px;
  background: #f5f7fa;
  border: 1px dashed #c0c4cc;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 36px;
  color: #909399;
  cursor: pointer;
  transition: all 0.3s;
}

.avatar-uploader-icon:hover {
  border-color: #409eff;
  color: #409eff;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
}

.user-basic-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.user-name {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
}

.user-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  color: #606266;
  font-size: 14px;
}

.user-role {
  background: #ecf5ff;
  color: #409eff;
  padding: 2px 10px;
  border-radius: 12px;
  font-size: 12px;
}

.user-stats {
  display: flex;
  gap: 40px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.profile-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #f0f0f0;
}

.profile-form,
.password-form {
  padding: 0 10px;
}

.form-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

.security-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.security-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 6px;
}

.security-label {
  font-size: 14px;
  color: #303133;
}

.security-status {
  flex: 1;
  display: flex;
  justify-content: center;
}

.security-action {
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .profile-header {
    flex-direction: column;
    align-items: center;
    text-align: center;
    padding: 20px;
  }
  
  .user-meta {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .user-stats {
    justify-content: center;
    gap: 20px;
  }
  
  .profile-content {
    grid-template-columns: 1fr;
  }
  
  .security-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .security-status {
    justify-content: flex-start;
  }
  
  .security-action {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>